﻿#include "VoiceTalk.h"

#include <QAudioFormat>
#include <QAudioInput>
#include <QAudioOutput>
#include <QPointer>
#include <QThread>

VoiceTalk::VoiceTalk(QObject* parent)
    : QObject(parent)
    , m_state(false)
{
}

void VoiceTalk::setState(bool state)
{
    m_state = state;
}

// 接收设备输入
void VoiceTalk::onGetVoiceInput()
{
    QAudioFormat audioFormat;
    audioFormat.setSampleRate(16000);                        // 设置采样率
    audioFormat.setChannelCount(1);                          // 设置通道数
    audioFormat.setSampleSize(16);                           // 设置采样大小
    audioFormat.setCodec("audio/pcm");                       // 设置编码方式
    audioFormat.setByteOrder(QAudioFormat::LittleEndian);    // 设置字节顺序
    audioFormat.setSampleType(QAudioFormat::UnSignedInt);    // 设置样本数据类型

    QPointer<QAudioInput> audioInput = new QAudioInput(audioFormat);
    QPointer<QIODevice> io = audioInput->start();
    char recv[4096];

    while(true) {
        if(m_state) {
            qint64 len1 = audioInput->bytesReady();
            if(len1 > 4096) {
                continue;
            }

            if(len1 > 0) {
                qint64 len2 = io->read(recv, len1);

                if(len2 > 0) {
                    QByteArray voiceArr;
                    voiceArr.resize(len2);
                    memcpy(voiceArr.data(), recv, len2);
                    emit sigVoiceTalkIn(voiceArr);
                }
            }
        } else {
            break;
        }

        QThread::msleep(1);
    }

    delete io;
    delete audioInput;
}

// 使用设备输出
void VoiceTalk::onGetVoiceOutput()
{
    QAudioFormat audioFormat;
    audioFormat.setSampleRate(16000);                        // 设置采样率
    audioFormat.setChannelCount(1);                          // 设置通道数
    audioFormat.setSampleSize(16);                           // 设置采样大小
    audioFormat.setCodec("audio/pcm");                       // 设置编码方式
    audioFormat.setByteOrder(QAudioFormat::LittleEndian);    // 设置字节顺序
    audioFormat.setSampleType(QAudioFormat::UnSignedInt);    // 设置样本数据类型

    QPointer<QAudioOutput> audioOutput = new QAudioOutput(audioFormat);
    QPointer<QIODevice> io = audioOutput->start();

    while(true) {
        if(m_state) {
            io->write(m_voice, m_voice.size());
        } else {
            break;
        }

        QThread::msleep(1);
    }

    delete io;
    delete audioOutput;
}

void VoiceTalk::setVoice(QByteArray voice)
{
    m_voice = voice;
}
